<!-- 管理员 -->
<template>
  <div class="app-container">
    <!-- <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item prop="name" label="关键字">
          <el-input
            v-model="queryParams.name"
            placeholder="角色名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <i-ep-refresh />
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div> -->

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" @click="handleOpenDialog()">
          <i-ep-plus />
          新增
        </el-button>
        <!-- <el-button
          type="danger"
          :disabled="ids.length === 0"
          @click="handleDelete()"
        >
          <i-ep-delete />
          批量删除
        </el-button> -->
      </template>

      <el-table
        ref="dataTableRef"
        loading="loading"
        :data="roleList"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          key="id"
          label="编号"
          align="center"
          prop="id"
          width="150"
        />
        <el-table-column
          key="username"
          label="用户名"
          align="center"
          prop="username"
          width="150"
        />

        <el-table-column
          key="name"
          label="姓名"
          width="150"
          align="center"
          prop="name"
        />

        <el-table-column
          key="role.roleName"
          label="角色"
          width="150"
          align="center"
          prop="role.roleName"
        />
        <el-table-column label="手机号码" align="center" width="180">
          <template #default="scope">
            <div v-if="scope.row.isPhone">
              {{ judgePhone(scope.row.phone.toString()) }}
              <Hide
                style="width: 1em; height: 1em; margin-left: 8px"
                @click="scope.row.isPhone = !scope.row.isPhone"
              />
            </div>
            <div v-else>
              {{ scope.row.phone }}
              <View
                style="width: 1em; height: 1em; margin-left: 8px"
                @click="scope.row.isPhone = !scope.row.isPhone"
              />
            </div>
          </template>
        </el-table-column>

        <el-table-column label="创建时间" align="center">
          <template #default="scope">
            <text>
              {{
                new Date(scope.row.createdAt)
                  .toISOString()
                  .replace("T", " ")
                  .substring(0, 19)
              }}
            </text>
          </template>
        </el-table-column>

        <el-table-column label="最后登录时间" align="center">
          <template #default="scope">
            <text>
              {{
                new Date(scope.row.lastLoginAt)
                  .toISOString()
                  .replace("T", " ")
                  .substring(0, 19)
              }}
            </text>
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="handleOpenDialog('possword', scope.row.id)"
            >
              <i-ep-refresh-left />
              重置密码
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              @click="handleOpenDialog(scope.row.id)"
            >
              <i-ep-edit />
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              link
              @click="handleDelete(scope.row)"
            >
              <i-ep-delete />
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.current"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <!-- 管理员表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="500px"
      @close="handleCloseDialog"
    >
      <el-form
        ref="roleFormRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="formData.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入电话" />
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select
            v-model="formData.roleName"
            @change="rolesSelectChange"
            value-key="roleId"
          >
            <el-option
              v-for="item in allRoles"
              :key="item.roleId"
              :label="item.roleName"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="dialog.title == '新增管理员'"
          label="密码"
          prop="password"
        >
          <el-input v-model="formData.password" placeholder="请输入密码" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 修改密码弹窗 -->
    <el-dialog
      v-model="dialog.posswordVisible"
      :title="dialog.title"
      width="500px"
      @close="handleClosePasswordDialog"
    >
      <el-form
        ref="passwordFormRef"
        :model="passwordFormData"
        :rules="passwordRules"
        label-width="100px"
      >
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input
            v-model="passwordFormData.oldPassword"
            placeholder="请输入旧密码"
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordFormData.newPassword"
            placeholder="请输入新密码"
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordFormData.confirmPassword"
            placeholder="请输入确认密码"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="hancleResetPassword">
            确 定
          </el-button>
          <el-button @click="handleClosePasswordDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Administrator",
  inheritAttrs: false,
});
import superAPI, { SuperPageQuery, SuperForm } from "@/api/system";
import rolesAPI, { RolesVO } from "@/api/role";
import { judgePhone } from "@/utils/helper";

const roleFormRef = ref(ElForm);
const passwordFormRef = ref(ElForm);

const loading = ref(false);
const ids = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<SuperPageQuery>({
  current: 1,
  pageSize: 10,
  name: "",
});

// 管理员表格数据
const roleList = ref<any>([]);
// 全部角色列表
const allRoles = ref<RolesVO[]>();
// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
  posswordVisible: false,
});
// 管理员表单
const formData = reactive<SuperForm>({
  roleId: undefined,
  roleName: "",
  username: "",
  password: "",
  name: "",
  phone: "",
});
// 修改密码表单
const passwordFormData = reactive<any>({
  id: undefined,
  oldPassword: "",
  newPassword: "",
  confirmPassword: "",
});
const rules = reactive({
  name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  phone: [
    {
      required: true,
      message: "请输入电话",
      trigger: "blur",
      pattern: /^1[3-9]\d{9}$/,
    },
  ],
  roleId: [{ required: true, message: "请输入角色", trigger: "blur" }],
  password: [
    {
      required: true,
      message: "请输入至少6位,字母+数字的密码",
      trigger: "blur",
      pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,}$/,
    },
  ],
});
const passwordRules = reactive({
  oldPassword: [
    {
      required: true,
      message: "请输入至少6位,字母+数字的旧密码",
      trigger: "blur",
      pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,}$/,
    },
  ],
  newPassword: [
    {
      required: true,
      message: "请输入至少6位,字母+数字的新密码",
      trigger: "blur",
      pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,}$/,
    },
  ],
  confirmPassword: [
    {
      required: true,
      message: "请输入至少6位,字母+数字的确认密码",
      trigger: "blur",
      pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,}$/,
    },
  ],
});

/** 查询 */
function handleQuery() {
  loading.value = true;
  superAPI
    .getSuperAdmin()
    .then((data) => {
      // console.log(data, "管理员列表");
      let newList = data.map((item) => ({
        ...item,
        isPhone: true,
      }));
      roleList.value = newList;
      total.value = data.length;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function handleResetQuery() {
  // queryFormRef.value.resetFields();
  queryParams.current = 1;
  handleQuery();
}

/** 打开角色弹窗 */
async function handleOpenDialog(val?: any, id?: string | number) {
  allRoles.value = await rolesAPI.getRoles();
  if (val == "possword" && id) {
    dialog.posswordVisible = true;
    dialog.title = "修压密码";
    passwordFormData.id = id;
  } else if (val == undefined) {
    dialog.visible = true;
    dialog.title = "新增管理员";
  } else {
    dialog.visible = true;
    dialog.title = "修改管理员";
    superAPI.getSuperInfo(val).then((res: any) => {
      let roles = allRoles.value?.find(
        (item) => item.roleId == res.user.roleId
      );
      Object.assign(formData, {
        ...res.user,
        roleName: roles?.roleName,
      });
    });
  }
}
/** 选中角色时触发 */
const rolesSelectChange = (item: any) => {
  formData.roleId = item.roleId;
  formData.roleName = item.roleName;
};
/** 提交管理员表单 */
function handleSubmit() {
  roleFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const roleId = formData.roleId;
      if (roleId) {
        superAPI
          .updateSuperAdmin(formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        superAPI
          .updateSuperAdmin(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}
/** 重置密码 */
function hancleResetPassword(row: { [key: string]: any }) {
  passwordFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      superAPI
        .modifySuperAdminPassword(passwordFormData.id, {
          oldPassword: passwordFormData.oldPassword,
          newPassword: passwordFormData.newPassword,
        })
        .then(() => {
          ElMessage.success("密码重置成功");
          handleClosePasswordDialog();
        })
        .finally(() => (loading.value = false));
    }
  });
}
/** 关闭管理员弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  roleFormRef.value.resetFields();
  roleFormRef.value.clearValidate();
  formData.roleId = undefined;
  formData.roleName = "";
  formData.password = "";
}
/** 关闭修改密码弹窗 */
function handleClosePasswordDialog() {
  dialog.posswordVisible = false;
  passwordFormRef.value.resetFields();
  passwordFormRef.value.clearValidate();
  passwordFormData.id = undefined;
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

/** 删除管理员 */
function handleDelete(role?: any) {
  const roleIds = [role.id || ids.value].join(",");
  if (!roleIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      superAPI
        .deleteSuperAdmin(roleIds, { username: role.username })
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

onMounted(() => {
  handleQuery();
});
</script>
